<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Cdkey;
use app\common\model\Exchange;
use app\common\model\Invites;
use app\common\model\Prizes;
use app\common\model\Record;
//use app\common\model\Reward;
use fast\Random;
use think\Config;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third','isLogin2','unique_rand','setPrizesNum','addPrizesInfo','getMykey'];
    protected $noNeedRight =['isLogin','getMyYq','addYqm','addPrizesInfo','getMyPrizes','editMyPrizesCode','addMyPrizesCode','getMyDh','getRecordList','getMyScore'];

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    //判断是否登录
    public function isLogin()
    {
        $token = $this->auth->getToken();
        if($token){
            $this->success('ok',$token);
        }
    }

    public function isLogin2()
    {
        if (!$this->auth->isLogin()) {
            $this->success('no');
        }else{
            $id = $this->auth->id;
            $find = \app\common\model\User::get($id);
            $this->success('ok',$find['f_yqm']);
        }
    }
    //提交邀请码
    public function addYqm()
    {
//        halt($this->unique_rand(1000000, 9999999, 1));
        $param = $this->request->param('yqm');
        if(!isset($param)){
            $this->error('邀请码不能为空');
        }
        if($param==''){
            $this->error('邀请码不能为空');
        }
        $uid = $this->auth->id;
        $user = \app\common\model\User::get($uid);
        if($param==='0'){
            $user->score = $user['score']+1;
            $user->f_yqm = 0;
            //生成唯一邀请码
            $user->yqm = $this->unique_rand(1000000, 9999999, 1)[0];
        }else{
            //根据邀请码查询用户
            $f_user = \app\common\model\User::where('yqm',$param)->find();
            if(empty($f_user)){
                $this->error('邀请码无效');
            }else{
                $user->score = $user['score']+1;
                $user->f_yqm = $param;
                $f_user->score = $f_user['score']+1;
                $f_user->save();
                $user->yqm = $this->unique_rand(1000000, 9999999, 1)[0];
                //添加到邀请记录表
                $data = [
                    'user_id'=>$f_user['id'],
                    'be_user_id'=>$uid,
                    'be_openid'=>$user['openid'],
                ];
                $model = new Invites();
                $model->allowField(true)->save($data);

            }
        }
        $user->save();
        $this->success('邀请码有效');

    }
    public function unique_rand($min, $max, $num) {
        $count = 0;
        $return = array();
        while ($count < $num) {
            $return[] = mt_rand($min, $max);
            $return = array_flip(array_flip($return));
            $count = count($return);
        }
        shuffle($return);
        return $return;
    }
    //抽奖，减少次数
    public function setPrizesNum()
    {
        if (!$this->auth->isLogin()) {
            $this->success('no',null,'201');
        }else{
            $id = $this->auth->id;
            $find = \app\common\model\User::get($id);
            $num = $find['score']-1;
            if($num<0){
                $this->success('no','积分不足');
            }else{
                $find->score = $num;
            }
            $find->save();
            $this->success('ok');
        }
    }
    //抽奖成功，添加记录
    public function addPrizesInfo()
    {
        $id = $this->request->param('id');


        //根据奖品id获取仓库id，根据仓库id获取key，如果key无则返回积分

        //查询商品仓库id
        $dfind = Prizes::get($id);

        if(empty($dfind)){
            $this->error('抽奖出错');
        }
        if($dfind['depot_id']==1){
            $this->error('谢谢参与');
        }
       //查询兑换码
        $find = Cdkey::where('depot_id',$dfind['depot_id'])->where('is_use','0')->orderRaw('rand()')->limit(1)->find();
        if(empty($find)){
            //库存没有，返回积分
            $user = \app\common\model\User::get($this->auth->id);
            $user->score = $user['score']+1;//一个积分抽一次奖
            $user->save();
            $this->error('没有库存');
        }
//        $find = $cdkey[0];
        //设置兑换码为使用
        $k = Cdkey::get($find['id']);
        $k->user_id = $this->auth->id;
        $k->is_use = '1';
        $k->save();

        //添加到中奖记录里面
        $data = [
            'user_id'=>$this->auth->id,
            'code_key'=>$k['code'],
            'name'=>$dfind['name'],
        ];
        (new Record())->allowField(true)->save($data);

        $this->success('ok',$find['code']);
    }

    //查询我的中奖记录
    public function getMyPrizes()
    {

        $param = $this->request->param('type')??0;

        $list = Cdkey::where('user_id',$this->auth->id)->order('updatetime desc')->whereNull('overduetime')->select();

        $this->success('ok',$list);
    }
    //隐藏用户兑换码
    public function editMyPrizesCode()
    {
        $id = $this->request->param('id');
        if(empty($id)){
            $this->error('操作错误');
        }
        $find= Cdkey::find($id);
        $find->overduetime = time();
        $find->save();
        $this->success('删除成功');
    }
    //兑换商品
    public function addMyPrizesCode()
    {
        $id = $this->request->param('id');
        $uid = $this->auth->id;
        //根据积分商品id查询当前所需夺嫂积分和商品仓库id
        $find = Prizes::get($id);

        $user = \app\common\model\User::get($uid);
        if($find['score']>$user['score']){
            $this->error('积分不足');
        }else{
            $cd = Cdkey::where('depot_id',$find['depot_id'])->where('is_use','0')->orderRaw('rand()')->limit(1)->find();
            if(empty($cd)){
                $this->error('库存不足');
            }
            $user->score = $user['score']-$find['score'];
            $user->save();

            $k = Cdkey::get($cd['id']);
            $k->user_id = $this->auth->id;
            $k->is_use = '1';
            $k->save();

            //添加到兑换记录
            $data = [
                'user_id'=>$this->auth->id,
                'depot_id'=>$find['depot_id'],
                'code_key'=>$cd['code'],
                'score'=>$find['score']
            ];
            $e = new Exchange();
            $e->allowField(true)->save($data);
        }
        $this->success('兑换成功');
    }

    //获取我的积分
    public function getMyScore()
    {
        if (!$this->auth->isLogin()) {
            $this->success('ok',0);
        }else{
            $uid = $this->auth->id;
            $user = \app\common\model\User::get($this->auth->id);
            $this->success('ok',$user['score']);
        }
    }
    //获取用户邀请码
    public function getMykey()
    {
        if (!$this->auth->isLogin()) {
            $this->success('ok','未登录');
        }else{
            $uid = $this->auth->id;
            $user = \app\common\model\User::get($this->auth->id);
            $this->success('ok',$user['yqm']??'无');
        }
    }
    //查询我的商品兑换
    public function getMyDh()
    {
        $list = Exchange::with('depot')->where('user_id',$this->auth->id)->select();
        $this->success('ok',$list);
    }
    //查询我的中奖兑换码
    public function getRecordList()
    {
        $list = Record::with('user')->where('user_id',$this->auth->id)->select();
        $this->success('ok',$list);
    }
    //获取我的邀请记录
    public function getMyYq()
    {
        //获取我的邀请记录
//        查询所有邀请记录
        $model = new \app\common\model\Invites();
        $list = $model->with('be_user')->where('user_id',$this->auth->id)->select();
        $this->success('ok',$list);
//        foreach ()

    }
}
